package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @author FCJ
 * @date 2020-01-10 19:41
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserDao userDao;

    @Override//根据用户名查询用户信息，同时查询角色关联和权限信息
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;
        }
        Set<Role> roles = roleDao.findRoleByUserId(user.getId());
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                Set<Permission> permissions = permissionDao.findByRoleId(role.getId());
                if (permissions != null && permissions.size() > 0) {
                    role.setPermissions(permissions);
                }

            }
            user.setRoles(roles);
        }


        return user;
    }

    @Override
    public Boolean updatePassword(Map map) {
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        String username = (String) map.get("username");
        String oldPassword = ((String) map.get("oldPassword"));
        User user1 = new User();
        user1.setUsername(username);
        String newPassword = (String) map.get("newPassword");
        user1.setPassword(bc.encode(newPassword));
        User user = userDao.findByUsername(username);
        if (user == null) {
            return false;
        }
        String passwordindb = user.getPassword();
        if (!bc.matches(oldPassword, passwordindb)) {
            return false;
        }

        try {
            userDao.updatePassword(user1);
            return true;
        } catch (Exception e) {
            return false;
        }


    }


}
